package com.lm.controller;

import com.lm.dao.LmUserLoginDao;
import com.lm.model.CheckCode;
import com.lm.model.LmUserLogin;
import com.lm.service.CheckCodeService;
import com.lm.service.LmUserLoginService;
import com.meirengu.common.PasswordEncryption;
import com.meirengu.common.StatusCode;
import com.meirengu.controller.BaseController;
import com.meirengu.model.Result;
import com.meirengu.utils.StringUtil;
import com.meirengu.utils.ValidatorUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("user")
public class LmUserLoginController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(LmUserLoginController.class);

    @Autowired
    LmUserLoginService lmUserLoginService;
    @Autowired
    CheckCodeService checkCodeService;
    @Autowired
    LmUserLoginDao lmUserLoginDao;

    /**
     * 登陆密码找回
     *
     * @param newPassword
     * @return
     */
    @RequestMapping(value = "password/reset", method = RequestMethod.POST)
    public Result retrievePassword(@RequestParam(value = "phone", required = false) String phone,
                                   @RequestParam(value = "check_code", required = false) String checkCode,
                                   @RequestParam(value = "new_password", required = false) String newPassword) {
        try {
            //verify params
            if (StringUtils.isEmpty(phone) || !ValidatorUtil.isMobile(phone)) {
                return super.setResult(StatusCode.MOBILE_FORMAT_ERROR, null, StatusCode.codeMsgMap.get(StatusCode.MOBILE_FORMAT_ERROR));
            }
            if (StringUtil.isEmpty(newPassword)) {
                return super.setResult(StatusCode.PASSWORD_IS_MALFORMED, null, StatusCode.codeMsgMap.get(StatusCode.PASSWORD_IS_MALFORMED));
            }
            //验证手机号是否注册
            LmUserLogin lmUserLogin = lmUserLoginService.detailByPhone(phone);
            if (lmUserLogin == null) {
                return super.setResult(StatusCode.USER_NOT_EXITS, null, StatusCode.codeMsgMap.get(StatusCode.USER_NOT_EXITS));
            }
            //验证验证码是否有效
            CheckCode code = checkCodeService.retrieve(phone, Integer.valueOf(checkCode));
            if (code == null) {
                return super.setResult(StatusCode.CAPTCHA_INVALID, null, StatusCode.codeMsgMap.get(StatusCode.CAPTCHA_INVALID));
            }
            if (code.getExpireTime().compareTo(new Date()) < 0) {
                return super.setResult(StatusCode.CAPTCHA_EXPIRE, null, StatusCode.codeMsgMap.get(StatusCode.CAPTCHA_EXPIRE));
            }
            code.setUse(true);
            code.setUsingTime(new Date());
            checkCodeService.update(code);

            lmUserLogin.setPassword(PasswordEncryption.createHash(newPassword));
            lmUserLogin.setUpdateDate(new Date());
            int result = lmUserLoginDao.update(lmUserLogin);
            if (result == 1) {
                return super.setResult(StatusCode.OK, null, StatusCode.codeMsgMap.get(StatusCode.OK));
            } else {
                return super.setResult(StatusCode.RECORD_NOT_EXISTED, null, StatusCode.codeMsgMap.get(StatusCode.RECORD_NOT_EXISTED));
            }
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数:phone:%s,checkCode:%s,newPassword:%s", phone, checkCode, newPassword);
            logger.error("LmUserLoginController retrievePassword throws Exceprion :{} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, null, StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }
    }

    /**
     * 修改昵称
     *
     * @param
     * @return
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public Result resetNickName(@RequestParam(value = "id", required = false) String id,
                                @RequestParam(value = "nick_name", required = false) String nickName,
                                @RequestParam(value = "portrait", required = false) String portrait) {
        try {
            //verify params
            if (StringUtils.isEmpty(id) || StringUtil.isEmpty(nickName)) {
                return super.setResult(StatusCode.MISSING_ARGUMENT, null, StatusCode.codeMsgMap.get(StatusCode.MISSING_ARGUMENT));
            }

            LmUserLogin lmUserLogin = lmUserLoginDao.detail(id);
            if (lmUserLogin == null) {
                return super.setResult(StatusCode.USER_NOT_EXITS, null, StatusCode.codeMsgMap.get(StatusCode.USER_NOT_EXITS));
            }
            if (!StringUtil.isEmpty(nickName)) {
                nickName = StringUtil.filterEmoji(nickName);
                if (nickName.length() > 12) {
                    //昵称限制12个字符
                    return super.setResult(StatusCode.USER_NICKNAME_TOLONG, null, StatusCode.codeMsgMap.get(StatusCode.USER_NICKNAME_TOLONG));
                }
                lmUserLogin.setNickName(nickName);
            }
            if (!StringUtil.isEmpty(portrait)) {
                lmUserLogin.setPortrait(portrait);
            }
            lmUserLogin.setUpdateDate(new Date());
            int flag = lmUserLoginDao.update(lmUserLogin);
            if (flag != 1) {
                return super.setResult(StatusCode.FAILED_UPDATE_USER, null, StatusCode.codeMsgMap.get(StatusCode.FAILED_UPDATE_USER));
            }
            lmUserLogin.setPassword("");
            return super.setResult(StatusCode.OK, lmUserLogin, StatusCode.codeMsgMap.get(StatusCode.OK));
        } catch (Exception e) {
            e.printStackTrace();
            String params = String.format("参数:id:%s,nickName:%s,portrait:%s", id, nickName, portrait);
            logger.error("LmUserLoginController resetNickName throws Exceprion :{} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, null, StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }
    }


}
